/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.seari.utils;

import com.twmacinta.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 *
 * @author sunzhu
 */
public class HashTool
{
    public static String getUrlHashPlain(int cid, String url)
    {
        //return "("+cid+")("+myBoard.bid+")"+url;
        return "(" + cid + ")"+ url;
    }

    public static String generateUrlHash(int cid, String url)
    {
        MD5 md5 = new MD5();
        md5.Update(getUrlHashPlain(cid,url));
        return md5.asHex();
    }

    public static String generateSimpleHash(String str)
    {
        MD5 md5 = new MD5();
        md5.Update(str);
        return md5.asHex();
    }

    public static String generateUrlGuid(String url)
    {
        return generateSimpleHash(url);
    }
    
    
    // 计算文件的 MD5 值
    public static String getFileMD5(File file)
    {
        if (!file.isFile())
        {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try
        {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1)
            {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            try
            {
                in.close();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    
    // 计算文件的 SHA-1 值
    public static String getFileSha1(File file)
    {
        if (!file.isFile())
        {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[8192];
        int len;
        try
        {
            digest = MessageDigest.getInstance("SHA-1");
            in = new FileInputStream(file);
            while ((len = in.read(buffer)) != -1)
            {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            try
            {
                in.close();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
